package com.laikan.reader.core.service;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.os.IBinder;
import android.text.TextUtils;
import android.widget.RemoteViews;
import com.laikan.library.managers.ToastMgr;
import com.laikan.reader.R;
import com.laikan.reader.core.bean.VersionDetialInfo;
import com.laikan.reader.core.utils.PublicUtil;
import com.socks.library.KLog;

import java.io.File;
import java.util.Locale;

/**
 * @param <T>
 *
 * @author wcg
 * @version 创建时间：2013-10-11 下午2:32:36
 * @Description 应用程序更新服务
 * @email spring.wang@itotemdeveloper.com
 * @company 北京爱图腾科技有限公司
 */
public class AppUpdateService extends Service {

    public static final String LEGALD_AILY_SD = Environment.getExternalStorageDirectory().getPath() + "/LaikanReader";
    public static final String UPDATE_DIR = LEGALD_AILY_SD + "/update";
    private NotificationManager manager;
    private Notification notif;
    private PendingIntent pendingIntent;
    private AppUpdateDownloader appUpdateDownloader;
    private VersionDetialInfo detailInfo;

    @Override
    public void onCreate() {
        manager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
        notif = new Notification();
        notif.icon = R.mipmap.ic_launcher;
        notif.flags = Notification.FLAG_AUTO_CANCEL;
        notif.tickerText = "下载开始";
        pendingIntent = null;
        Intent intent = new Intent();
        pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        appUpdateDownloader = new AppUpdateDownloader(this);
        notif.contentIntent = pendingIntent;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        if (null != intent) {
            detailInfo = (VersionDetialInfo)intent.getSerializableExtra("updateBean");
            if (null != detailInfo) {
                appUpdateDownloader.download(detailInfo.getUrl());
            }
        }

        return super.onStartCommand(intent, flags, startId);
    }

    public IBinder onBind(Intent intent) {
        return null;
    }

    private void removeFile() {
        File file = new File(UPDATE_DIR, "temp.apk");
        boolean b = file.exists();
        KLog.e("cxm", "b----" + b);
        boolean delete = file.delete();
        KLog.e("cxm", "delete----" + delete);
    }

    private class AppUpdateDownloader extends FileDownloader {

        public AppUpdateDownloader(Context ctx) {
            super(ctx);
        }

        @Override
        public void onStart(String url) {
            notif.contentView = new RemoteViews(getPackageName(), R.layout.content_view);
            notif.contentView.setTextViewText(R.id.tvName, "最新安装包");
            notif.contentView.setTextViewText(R.id.tvProgress, "0%");
            notif.contentView.setProgressBar(R.id.content_view_progress, 100, 0, false);
            manager.notify(1, notif);
        }

        @Override
        public void onProgress(String url, int p) {
            notif.contentView = new RemoteViews(getPackageName(), R.layout.content_view);
            notif.contentView.setTextViewText(R.id.tvName, "最新安装包");
            notif.contentView.setTextViewText(R.id.tvProgress, p + "%");
            notif.contentView.setProgressBar(R.id.content_view_progress, 100, p, false);
            manager.notify(1, notif);
        }

        @Override
        public void onFinish(String url) {
            notif.contentView = new RemoteViews(getPackageName(), R.layout.content_view);
            notif.contentView.setTextViewText(R.id.tvName, "最新安装包");
            notif.contentView.setTextViewText(R.id.tvProgress, "100%");
            notif.contentView.setProgressBar(R.id.content_view_progress, 100, 100, false);
            manager.notify(1, notif);
            ToastMgr.showShortToast("下载完成");
            // 启动安装程序
            installApk(new File(UPDATE_DIR + "/temp.apk"));
        }

        @Override
        public void onFailure(String url) {
            ToastMgr.showShortToast("下载失败");
        }

        private void installApk(File f) {
            Intent intent = new Intent();
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setAction(android.content.Intent.ACTION_VIEW);
            String type = getMIMEType(f);
            intent.setDataAndType(Uri.fromFile(f), type);
            // ((Activity) mContext).startActivityForResult(intent, 1);
            startActivity(intent);
        }

        private String getMIMEType(File f) {
            String type = "";
            String fName = f.getName();
            String end = fName.substring(fName.lastIndexOf(".") + 1, fName.length()).toLowerCase(Locale.getDefault());
            if (end.equals("m4a") || end.equals("mp3") || end.equals("mid") || end.equals("xmf") || end.equals("ogg") || end.equals("wav")) {
                type = "audio";
            }else if (end.equals("3gp") || end.equals("mp4")) {
                type = "video";
            }else if (end.equals("jpg") || end.equals("gif") || end.equals("png") || end.equals("jpeg") || end.equals("bmp")) {
                type = "image";
            }else if (end.equals("apk")) {
                type = "application/vnd.android.package-archive";
            }else {
                type = "*";
            }
            if (end.equals("apk")) {
            }else {
                type += "/*";
            }
            return type;
        }

        /**
         * 下载此URL文件
         *
         * @param url
         */
        public void download(String url) {
            if (TextUtils.isEmpty(url)) {
                url = "";
            }
            if (PublicUtil.isHaveSDCard()) {
                removeFile();
                downloadHandler.download(url, new File(UPDATE_DIR), "temp.apk");
            }else {
                ToastMgr.showShortToast("无SD卡，不可执行更新程序");
            }
        }
    }
}
